<template>
  <div class="import">
    <UploadExcel :on-success="handleSuccess" :before-upload="beforeUpload" />
  </div>
</template>

<script>
import { formatExcelDate } from '@/utils'
import { addEmployees } from '@/api/employee'

export default {
  name: 'Import',
  components: {},
  data() {
    return {

    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    async handleSuccess({ results, header }) {
      const data = this.transExcel(results)
      try {
        const res = await addEmployees(data)
        this.$message.success(res.message)
        // 回到上一次的路由
        this.$router.back()
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    transExcel(results) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      return results.map(item => {
        const userInfo = {}
        Object.keys(item).forEach(key => {
          // 现在是 key 是中文
          if (mapInfo[key] === 'timeOfEntry' || mapInfo[key] === 'correctionTime') {
            userInfo[mapInfo[key]] = new Date(formatExcelDate(item[key]))
          } else {
            userInfo[mapInfo[key]] = item[key] // 将原来中文对应的值，赋值给原来英文对应的值
          }
        })
        return userInfo
      })
    }
  }
}
</script>

<style lang='scss' scoped>
.import {
  margin-top: 100px;
}
</style>
